import { debounce, intersection, difference } from 'lodash'
import axios from 'axios'

let MAPINS = null;
let currentSelectedMMSI = '';
// 视角范围内的船只的 id
let currentAISMMSIArr = [];
const SHOULDFORMATS_TABLE = [
  // 船长
  "LENGTH",
  // 船宽
  "WIDTH",
  // 定位点的左舷距
  "LEFT_X",
  // 点位点的尾舷距
  "TRAIL",
  // 经度
  "LAT",
  // 纬度
  "LON",
  // 对地速度
  "SOG",
  // 对地航向
  "COG",
  // 航首向
  "HDG",
  // 地转偏向率
  "ROT"
]
const MapServiceUrl =
  'http://10.167.74.15:8090/iserver/services/map-ShanDongGang-AIS/rest/maps/AIS';
// ok 数据服务
const DataService = {
  // url: 'http://10.167.74.15:8090/iserver/services/data-ShanDongGang-AIS/rest/data',
  url: 'http://192.168.1.118:8090/iserver/services/data-GIS-Data-PG/rest/data',
  // datasetNames: ['ShanDongGang:AIS'],
  datasetNames: ['GIS-Data:AIS']
};
// ok 标签类
class LabelCustom {
  constructor(x, y, radius, height, byteWidth, name) {
    this.center = {
      x,
      y
    }; //中心坐标
    this.virtualReact = {
      maxX: 0,
      maxY: 0,
      minX: 0,
      minY: 0,
      width: 0,
      height: 0
    };
    this.show = true; //是否显示
    this.text = name;
    this.textReact = {
      width: 0,
      height: 0
    };
    this.radius = radius + 2; //间距
    this.padding = 0;
    this.aIndex = 0;
    this.align = 'center';
    if (!name) return;
    this._getRectangle(height * 2, byteWidth - 0.6);
  }
  getCurrentRect() {
    let result = null;
    switch (this.aIndex.toString()) {
      case '0':
        result = this._getRightAnchor();
        break;
      case '1':
        result = this._getBottomAnchor();
        break;
      case '2':
        result = this._getLeftAnchor();
        break;
      case '3':
        result = this._getTopAnchor();
        break;
      default:
        result = this._getCenterRectangle();
        break;
    }
    return result;
  }
  // 轮转方位
  next() {
    this.aIndex++;
    // 如果 4 个方位都没有合适的，就隐藏该标签
    if (this.aIndex > 3) {
      this.show = false;
    }
    return this.getCurrentRect();
  }
  _getTrueLength(str) {
    //获取字符串的真实长度（字节长度）
    let len = str.length,
      trueLen = 0;
    for (let x = 0; x < len; x++) {
      if (str.charCodeAt(x) > 128) {
        trueLen += 2;
      } else {
        trueLen += 1;
      }
    }
    return trueLen;
  }
  /**
   * 判断分位是否相交
   * @param {*} target
   */
  isAnchorMeet(target) {
    let react = this.getCurrentRect(),
      targetReact = target.getCurrentRect();
    if (
      react.minX < targetReact.maxX &&
      targetReact.minX < react.maxX &&
      react.minY < targetReact.maxY &&
      targetReact.minY < react.maxY
    ) {
      return true;
    }
    return false;
  }
  _getCenterRectangle() {
    return {
      minX: this.center.x - this.radius,
      maxX: this.center.x + this.radius,
      minY: this.center.y - this.radius,
      maxY: this.center.y + this.radius
    };
  }
  _getRectangle(height, byteWidth) {
    let width = this._getTrueLength(this.text) * byteWidth;
    this.textReact = {
      width: width + this.padding * 2,
      height: height
    };
  }
  _getLeftAnchor() {
    let x = this.center.x - this.radius - this.textReact.width,
      y = this.center.y - this.radius - this.textReact.height / 2,
      diam = this.radius * 2,
      maxH = diam > this.textReact.height ? diam : this.textReact.height;
    this.align = 'right';

    return {
      x,
      y,
      minX: x,
      maxX: this.center.x + this.radius,
      minY: this.center.y - maxH / 2,
      maxY: this.center.y + maxH / 2
    };
  }
  _getRightAnchor() {
    let x = this.center.x + this.radius,
      y = this.center.y - this.textReact.height / 2,
      diam = this.radius * 2,
      maxH = diam > this.textReact.height ? diam : this.textReact.height;
    this.align = 'left';
    return {
      x,
      y,
      minX: this.center.x - this.radius,
      maxX: this.center.x + this.radius + this.textReact.width,
      minY: this.center.y - maxH / 2,
      maxY: this.center.y + maxH / 2
    };
  }
  _getTopAnchor() {
    let x = this.center.x - this.textReact.width / 2,
      y = this.center.y - this.radius - this.textReact.height,
      diam = this.radius * 2,
      maxW = diam > this.textReact.width ? diam : this.textReact.width;
    this.align = 'right';
    return {
      x,
      y,
      minX: this.center.x - maxW / 2,
      maxX: this.center.x + maxW / 2,
      minY: this.center.y - this.radius - this.textReact.height,
      maxY: this.center.y + this.radius
    };
  }
  _getBottomAnchor() {
    let x = this.center.x - this.textReact.width / 2,
      y = this.center.y + this.radius,
      maxW = this.radius > this.textReact.width ? this.radius : this.textReact.width;
    this.align = 'left';
    return {
      x,
      y,
      minX: this.center.x - maxW / 2,
      maxX: this.center.x + maxW / 2,
      minY: this.center.y - this.radius,
      maxY: this.center.y + this.radius + this.textReact.height
    };
  }
}
function rotate(array, r, polygonCenter) {
  const currentRotation = getRotation(array[0] - polygonCenter[0], array[1] - polygonCenter[1]);
  const length = Math.sqrt(Math.pow(array[0] - polygonCenter[0], 2) + Math.pow(array[1] - polygonCenter[1], 2));
  const newRotation = currentRotation - r;
  const x = polygonCenter[0] + length * Math.cos(newRotation);
  const y = polygonCenter[1] + length * Math.sin(newRotation);
  return [x, y];
}
function getRotation(dx, dy) {
  var rot = 0;
  if (dx == 0 && dy == 0) { return 0 };
  if (dy == 0) { rot = dx > 0 ? 0 : Math.PI }
  else if (dx == 0) { rot = dy > 0 ? 0.5 * Math.PI : 1.5 * Math.PI }
  else {
    var rot = Math.atan(dy / dx);
    if (dx < 0 && dy > 0) rot += Math.PI;
    if (dx < 0 && dy < 0) rot += Math.PI;
    if (dx > 0 && dy < 0) rot += 2 * Math.PI;
  }
  return rot;
}
// 获取调整之后的船的朝向
// 调整规则：船舶方向，小于 360 度用hdg，大于 360 度用cog
// 注意 hdg 跟 sog 需要先除以 100
function getComputedShipHeading({ HDG, COG }) {
  const HDG_ = HDG / 100;
  const COG_ = COG / 100;
  return HDG_ > 360 ? COG_ : HDG_;
}
function DynamicShip({ map }) {
  if (DynamicShip.getIns()) {
    return DynamicShip.ins
  }
  DynamicShip.ins = this;
  MAPINS = map;
  this.AISLayer = null;
  this.TEXTLayer = null;
  this.initMap()
}
// ok 获取标签的位置
function getLabelPosition({ features, zoom }) {
  const labels = [];
  let radius = 0;
  switch (zoom) {
    case 18:
      radius = 10;
      break;
    case 17:
      radius = 60;
      break;
    case 16:
      radius = 110;
      break;
    case 15:
      radius = 180;
      break;
    case 14:
      radius = 270;
      break;
    case 13:
      radius = 300;
      break;
    case 12:
      radius = 500;
      break;
  }
  for (let i = 0; i < features.length; i++) {
    const ship = features[i];
    const position = ship.get('position');
    const attr = ship.get('attribute');
    attr.LENGTH = String(attr.LENGTH)
    const label_ = new LabelCustom(position[0], position[1], radius, 22, 1, attr.LENGTH || attr.CNNAME || attr.NAME);
    label_.shipPosition = position;
    labels.push(label_)
  }
  //x排序从小到大
  labels.sort((a, b) => {
    return b.center.x - a.center.x;
  });

  let meet;
  do {
    meet = false;
    let temp2;
    for (let i = 0; i < labels.length; i++) {
      let temp = labels[i];
      for (let j = 0; j < labels.length; j++) {
        temp2 = labels[j];
        if (temp2 != temp && temp.show && temp2.show && temp.isAnchorMeet(temp2)) {
          temp.next();
          meet = true;
          break;
        }
      }
    }
  } while (meet);
  return labels;
}
// 获取实例
DynamicShip.getIns = function () {
  return DynamicShip.ins;
}
// 获取实例
DynamicShip.create = function ({ map }) {
  return new DynamicShip({ map })
}
// 销毁
DynamicShip.prototype.destroy = function () {
}
// 初始化
DynamicShip.prototype.initMap = function () {
  if(!MAPINS) { return }
  const that = this;
  // 矢量图层
  this.AISLayer = new ol.layer.Vector({
    id: 'AISLayer',
    minZoom: 10,
    source: new ol.source.Vector()
  });
  // 文本图层
  this.TEXTLayer = new ol.layer.Vector({
    id: 'TEXTLayer',
    minZoom: 10,
    source: new ol.source.Vector(),
  });

  this.AISLayer.setZIndex(10)
  this.TEXTLayer.setZIndex(10)

  MAPINS.addLayer(this.AISLayer);
  MAPINS.addLayer(this.TEXTLayer);
  that.getAISData();
  MAPINS.on('moveend', function () {
    const zoom = MAPINS.getView().getZoom();
    document.title =  zoom;
    if (zoom < 11) {
      return
    }
    that.getAISData();
  });
  MAPINS.on('click', function (evt) {
    const highLightColor = '#f00';
    const normalColor = '#666';
    //点击选中船
    // const currentZoom = MAPINS.getView().getZoom();
    const feature = MAPINS.forEachFeatureAtPixel(evt.pixel, function (feature) { return feature; });
    const oldFeature = that.AISLayer.getSource().getFeatureById(currentSelectedMMSI);
    if (oldFeature) {
      oldFeature.set('shipStrokeColor', normalColor);
      if (oldFeature.get('shapeType') === 'ship') {
        const style = oldFeature.getStyle();
        const stroke = style.getStroke();
        stroke.setColor(normalColor);
        oldFeature.setStyle(style);
      } else {
        that.renderTriSymbol(oldFeature)
      }
    }
    if (!feature) {
      currentSelectedMMSI = '';
      return
    }

    const attr = feature.get('attribute')
    if (attr) {
      currentSelectedMMSI = attr.MMSI;
    }

    feature.set('shipStrokeColor', highLightColor);
    if (feature.get('shapeType') === 'ship') {
      const style = feature.getStyle();
      const stroke = style.getStroke();
      stroke.setColor(highLightColor);
      feature.setStyle(style);
    } else {
      that.renderTriSymbol(feature)
    }
  });
  MAPINS.on('pointermove', debounce(function (event) {
    const pixel = MAPINS.getEventPixel(event.originalEvent);
    const hit = MAPINS.hasFeatureAtPixel(pixel);
    if (pixel && hit) {
      MAPINS.getTargetElement().style.cursor = 'pointer';
    } else {
      MAPINS.getTargetElement().style.cursor = '';
    }
  }, 100));
}
// ok 将必要的数据数字化
DynamicShip.prototype.formatAISData = function (arr) {
  const timeNow = Date.now();
  if (!arr || !arr.length) { return }
  const freshData = this.clearAISLayerInDiff(arr);
  for (let i = 0; i < arr.length; i++) {
    const data = arr[i];
    const pro = data.properties;
    SHOULDFORMATS_TABLE.forEach(v => {
      pro[v] = Number(pro[v])
      if (Number.isNaN(pro[v])) {
        pro[v] = 0;
      }
    });
    this.updateSingleShipData({
      isFresh: freshData.indexOf(pro.MMSI) !== -1,
      data: data,
      timeNow: timeNow
    });
  }
}
// ok 根据两次请求数据的比对结果差异化删除不在屏幕内的船舶
DynamicShip.prototype.clearAISLayerInDiff = function (newShips) {
  const AISLayerSource = this.AISLayer.getSource();
  const res = newShips.map(v => {
    return v.properties.MMSI
  });
  // 交集数据
  const intersectionData = intersection(currentAISMMSIArr, res);
  // 需要删除的数据，因为不在当前视角范围内
  const shouldDeletedData = difference(currentAISMMSIArr, intersectionData);
  // 需要新增的数据，因为是新获取的
  const refreshData = difference(res, intersectionData);
  // 删除不需要的数据
  if (shouldDeletedData.length) {
    for (let i = 0; i < shouldDeletedData.length; i++) {
      const item = shouldDeletedData[i];
      const feature = AISLayerSource.getFeatureById(item);
      if (feature) {
        AISLayerSource.removeFeature(feature)
      }
    }
  }
  currentAISMMSIArr = res;
  return refreshData
}
// ok 添加一条船只数据
DynamicShip.prototype.updateSingleShipData = function ({ isFresh, data, timeNow }) {
  const pro = data.properties;
  const dx = pro.LEFT_X / 10;
  const dy = pro.TRAIL / 10;
  const width = pro.WIDTH / 10;
  const length = pro.LENGTH / 10;
  const trans = ol.proj.transform([pro.LON / 1000000, pro.LAT / 1000000], 'EPSG:4326', 'EPSG:3857');
  const lon = trans[0] + width / 2 - dx;
  const lat = trans[1] + length / 2 - dy;
  const pos = rotate([lon, lat], (((pro.HDG / 100) % 360) / 180) * Math.PI, trans);
  // 是否永远显示三角符号
  const alwaysTriSymbol = pro.LENGTH > 5000 || (pro.LENGTH / pro.WIDTH) > 9.5;
  // 处理船舶朝向问题
  let direction = 0;
  if (pro.SOG >= 514.4) {
    if (pro.ROT == 0) {
      direction = 1;
    }
    if (pro.ROT > 0) {
      direction = 2;
    }
    if (pro.ROT < 0) {
      direction = 3;
    }
  }

  // 处理时间问题，对应船舶颜色问题
  // 毫秒 -> 分钟
  const timeDiffer = (timeNow - new Date(pro.LASTTIME)) / (1000 * 60)
  let shipFillColor = "#9A9A9A";
  if (timeDiffer <= 30) {
    shipFillColor = '#FCFF7D';
  } else if (timeDiffer <= 120) {
    shipFillColor = '#54CA3A';
  }
  const geometry = new ol.geom.Point(pos)
  if (isFresh) {
    // 合成数据
    const shape = new ol.Feature({
      geometry: geometry,
      // 属性信息
      attribute: pro,
      // 是否总是展示三角形
      alwaysTriSymbol: alwaysTriSymbol,
      // 朝向
      direction: direction,
      // 填充颜色
      shipFillColor: shipFillColor,
      // 边线颜色
      shipStrokeColor: currentSelectedMMSI === pro.MMSI ? '#ff0000' : '#000000',
      // 位置
      position: pos,
      // 当前展示的外形类型 tri -> 三角 ship -> 船型
      shapeType: 'tri'
    });
    shape.setId(pro.MMSI);
    this.AISLayer.getSource().addFeature(shape);
  } else {
    const shape = this.AISLayer.getSource().getFeatureById(pro.MMSI);
    if (!shape) { return }
    shape.set('geometry', geometry);
    shape.set('attribute', pro);
    shape.set('alwaysTriSymbol', alwaysTriSymbol);
    shape.set('direction', direction);
    shape.set('position', pos);
    shape.set('shipFillColor', shipFillColor);
  }
}
// ok 渲染三角形
DynamicShip.prototype.renderTriSymbol = function (feature) {
  const attr = feature.get('attribute');
  if (!attr) { return }
  const direction = feature.get('direction');
  const shipFillColor = feature.get('shipFillColor');
  const shipStrokeColor = feature.get('shipStrokeColor');
  const position = feature.get('position');
  let w, h;
  let paths;
  switch (direction) {
    case 0:
      w = 11;
      h = 21;
      paths = [
        [5, 21],
        [0, 1],
        [10, 1],
        [5, 21]
      ];
      break;
    case 1:
      w = 11;
      h = 37;

      paths = [
        [5, 37],
        [5, 21],
        [0, 1],
        [10, 1],
        [5, 21],
        [5, 37]
      ];
      break;
    case 2:
      w = 11;
      h = 37;

      paths = [
        [0, 36],
        [5, 36],
        [5, 21],
        [0, 1],
        [10, 1],
        [5, 21],
        [5, 36],
        [0, 36]
      ];
      break;
    case 3:
      w = 11;
      h = 37;

      paths = [
        [10, 36],
        [5, 36],
        [5, 21],
        [0, 1],
        [10, 1],
        [5, 21],
        [5, 36],
        [10, 36]
      ];
      break;
    default:
      w = 11;
      h = 21;
      paths = [
        [5, 21],
        [0, 1],
        [10, 1],
        [5, 21]
      ];
      break;
  }

  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  canvas.width = w;
  canvas.height = h;
  context.lineWidth = 1;
  context.beginPath();
  context.moveTo(paths[0][0], paths[0][1]);

  for (let i = 1; i < paths.length; i++) {
    context.lineTo(paths[i][0], paths[i][1]);
  }
  context.fillStyle = shipFillColor;
  context.fill();
  context.strokeStyle = currentSelectedMMSI === attr.MMSI ? shipStrokeColor : '#000000';
  context.stroke();
  context.closePath();
  feature.setGeometry(new ol.geom.Point(position));
  if (direction === 0) {
    feature.setStyle(new ol.style.Style({
      image: new ol.style.Icon({
        img: canvas,
        imgSize: [canvas.width, canvas.height],
        rotation: Math.PI + ((getComputedShipHeading(attr) % 360) / 180) * Math.PI
      })
    }))
    return
  }
  feature.setStyle(new ol.style.Style({
    image: new ol.style.Icon({
      img: canvas,
      offsetOrigin: 'top-left',
      offset: [0, -16],
      imgSize: [canvas.width, canvas.height + 16],
      rotation: Math.PI + ((getComputedShipHeading(attr) % 360) / 180) * Math.PI
    })
  }))
}
// ok 渲染船只的形状
DynamicShip.prototype.renderShipSymbol = function (feature) {
  const attr = feature.get('attribute');
  const geometry = feature.get('geometry');
  const position = feature.get('position');
  const direction = feature.get('direction');
  const shipFillColor = feature.get('shipFillColor');
  const shipStrokeColor = feature.get('shipStrokeColor');
  const width = attr.WIDTH * 1 / 10;
  const height = attr.LENGTH * 1 / 10;
  const lon = position[0];
  const lat = position[1];
  let points;
  switch (direction) {
    case 0:
      points = [
        [lon, lat + height / 2],
        [lon - width * 0.3, lat + height * 0.4],
        [lon - width / 2, lat + height * 0.3],
        [lon - width / 2, lat - height * 0.45],
        [lon - width * 0.35, lat - height / 2],
        [lon + width * 0.35, lat - height / 2],
        [lon + width / 2, lat - height * 0.45],
        [lon + width / 2, lat + height * 0.3],
        [lon + width * 0.3, lat + height * 0.4],
        [lon, lat + height / 2]
      ];
      break;
    case 1:
      points = [
        [lon, lat + height / 2],
        [lon - width * 0.3, lat + height * 0.4],
        [lon - width / 2, lat + height * 0.3],
        [lon - width / 2, lat - height * 0.45],
        [lon - width * 0.35, lat - height / 2],
        [lon + width * 0.35, lat - height / 2],
        [lon + width / 2, lat - height * 0.45],
        [lon + width / 2, lat + height * 0.3],
        [lon + width * 0.3, lat + height * 0.4],
        [lon, lat + height / 2],
        [lon, lat + height / 2 + 30],
        [lon, lat + height / 2 + 30]
      ];
      break;
    case 2:
      points = [
        [lon, lat + height / 2],
        [lon - width * 0.3, lat + height * 0.4],
        [lon - width / 2, lat + height * 0.3],
        [lon - width / 2, lat - height * 0.45],
        [lon - width * 0.35, lat - height / 2],
        [lon + width * 0.35, lat - height / 2],
        [lon + width / 2, lat - height * 0.45],
        [lon + width / 2, lat + height * 0.3],
        [lon + width * 0.3, lat + height * 0.4],
        [lon, lat + height / 2],
        [lon, lat + height / 2 + 30],
        [lon + 7, lat + height / 2 + 30],
        [lon, lat + height / 2 + 30]
      ];
      break;
    case 3:
      points = [
        [lon, lat + height / 2],
        [lon - width * 0.3, lat + height * 0.4],
        [lon - width / 2, lat + height * 0.3],
        [lon - width / 2, lat - height * 0.45],
        [lon - width * 0.35, lat - height / 2],
        [lon + width * 0.35, lat - height / 2],
        [lon + width / 2, lat - height * 0.45],
        [lon + width / 2, lat + height * 0.3],
        [lon + width * 0.3, lat + height * 0.4],
        [lon, lat + height / 2],
        [lon, lat + height / 2 + 30],
        [lon - 7, lat + height / 2 + 30],
        [lon, lat + height / 2 + 30]
      ];
      break;
    default:
      points = [
        [lon, lat + height / 2],
        [lon - width * 0.3, lat + height * 0.4],
        [lon - width / 2, lat + height * 0.3],
        [lon - width / 2, lat - height * 0.45],
        [lon - width * 0.35, lat - height / 2],
        [lon + width * 0.35, lat - height / 2],
        [lon + width / 2, lat - height * 0.45],
        [lon + width / 2, lat + height * 0.3],
        [lon + width * 0.3, lat + height * 0.4],
        [lon, lat + height / 2]
      ];
      break;
  }
  const polygon = new ol.geom.Polygon([points]);
  feature.setGeometry(polygon);
  polygon.rotate((-(getComputedShipHeading(attr) % 360) / 180) * Math.PI, position);
  polygon.scale(1.25, 1.25)
  feature.setStyle(
    new ol.style.Style({
      fill: new ol.style.Fill({
        color: shipFillColor
      }),
      stroke: new ol.style.Stroke({
        color: currentSelectedMMSI === attr.MMSI ? shipStrokeColor : '#000000',
        width: 1
      })
    })
  );
}
// ok 渲染数据
DynamicShip.prototype.renderShipData = function () {
  const zoom = MAPINS.getView().getZoom();
  // 计算当前视图状态的范围和传递的框大小。
  const extent = MAPINS.getView().calculateExtent(MAPINS.getSize());
  const source = this.AISLayer.getSource();
  const features = source.getFeaturesInExtent(extent);
  if (!features) { return }
  this.rednerTextData({ features, zoom, extent });
  if ([11, 12, 13].indexOf(zoom) !== -1) {
    features.forEach(feature => {
      feature.set('shapeType', 'tri')
      this.renderTriSymbol(feature);
    })
    return
  }
  for (let i = 0; i < features.length; i++) {
    const feature = features[i];
    const alwaysTriSymbol = feature.get('alwaysTriSymbol')
    const attr = feature.get('attribute')
    if (alwaysTriSymbol) {
      feature.set('shapeType', 'tri')
      this.renderTriSymbol(feature);
    } else {
      // 是否是船类型
      let shipSign = false;
      if (zoom == 14) { shipSign = attr.LENGTH > 2000 };
      if (zoom == 15) { shipSign = attr.LENGTH > 1000 };
      if (zoom == 16) { shipSign = attr.LENGTH > 800 };
      if (zoom >= 17) { shipSign = attr.LENGTH > 350 };
      if (shipSign) {
        feature.set('shapeType', 'ship')
        this.renderShipSymbol(feature)
      } else {
        feature.set('shapeType', 'tri')
        this.renderTriSymbol(feature);
      }
    }
  }
}
// ok 文本标签
DynamicShip.prototype.rednerTextData = function ({ features, zoom, extent }) {
  if (!this.TEXTLayer) { return }
  this.TEXTLayer.getSource().clear();
  if (zoom < 13) { return }
  const labelsVir = getLabelPosition({ features, zoom }).filter(v => v.show)
  for (let i = 0; i < labelsVir.length; i++) {
    const labelVir = labelsVir[i];
    const position = labelVir.center;
    const pixel = labelVir.getCurrentRect();
    // const attr = ship.get('attribute');
    // const HDG_USE = getComputedShipHeading(attr);
    // const angle = ((60 - HDG_USE) % 360) * Math.PI / 180;
    // const dx = zoom * 5 * Math.cos(angle);
    // const dy = zoom * 5 * Math.sin(angle);
    const shapeOfName = new ol.Feature({
      geometry: new ol.geom.Point([pixel.x, pixel.y]),
      type: 'shapeOfName',
      shipPosition: position,
    });

    shapeOfName.setStyle(new ol.style.Style({
      text: new ol.style.Text({
        font: 'bold 14px 微软雅黑',
        text: labelVir.text,
        fill: new ol.style.Fill({ color: '#345' }),
        overflow: true,
        // textAlign: (HDG_USE + 90) % 360 < 180 ? 'left' : 'right',
        textAlign: labelVir.align,
        padding: [4, 4, 0, 4],
        backgroundFill: new ol.style.Fill({ color: '#fff' }),
        backgroundStroke: new ol.style.Stroke({ color: '#345' })
      })
    }))
    this.TEXTLayer.getSource().addFeature(shapeOfName);
    const shapeOfLine = new ol.Feature({
      geometry: new ol.geom.LineString([[pixel.x, pixel.y], labelVir.shipPosition]),
      type: 'shapeOfLine'
    });
    shapeOfLine.setStyle(new ol.style.Style({
      stroke: new ol.style.Stroke({
        width: 1,
        color: '#345'
      })
    }))
    this.TEXTLayer.getSource().addFeature(shapeOfLine);
  }
}
// ok 接收数据
DynamicShip.prototype.getAISData = function () {
  if (!MAPINS) { return }
  // const extent = MAPINS.getView().calculateExtent(MAPINS.getSize());
  // const boundsParam = new ol.supermap.GetFeaturesByBoundsParameters({
  //   datasetNames: DataService.datasetNames,
  //   bounds: extent,
  //   toIndex: -1,
  //   fields: [
  //     "SHIPID",
  //     "MMSI",
  //     "NAME",
  //     "LENGTH",
  //     "WIDTH",
  //     "LEFT_X",
  //     "TRAIL",
  //     "LAT",
  //     "LON",
  //     "SOG",
  //     "COG",
  //     "HDG",
  //     "ROT",
  //     "LASTTIME",
  //     "CNNAME"
  //   ],
  //   hasGeometry: false
  // });
  axios.get('./files/fake.json').then(res => {
    this.formatAISData(res.data);
    this.renderShipData();
  })
  // return
  // new ol.supermap
  //   .FeatureService(DataService.url)
  //   .getFeaturesByBounds(boundsParam)
  //   .then(function (serviceResult) {
  //     if (serviceResult.type !== 'processCompleted') {
  //       return
  //     }
  //     let features = serviceResult.result.features.features;
  //     if (!features || !features.length) { return }
  //     formatAISData(features);
  //     renderShipData();
  //   });
}
export {
  DynamicShip
}
